package sk.gtug.pivoplus.malepivo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import sk.gtug.pivoplus.malepivo.model.GeocodeResponse;
import sk.gtug.pivoplus.malepivo.model.GeocodeResponseResult;
import sk.gtug.pivoplus.malepivo.model.GeocodeResponseResult.GeocodeResponseResultColumns;
import sk.gtug.pivoplus.malepivo.utils.LocationHelper;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class LocationNew extends Activity {
		
	//DBAdapter mDBAdapter;
	ListView mListView;

	View mLoadingView;
	View mEmptyView;
	LinearLayout mLayout;
	
	String[] streets = new String[]{
			"Banskobystrická",
			"Bezručova",
			"Biela",
			"Dobrovičova",
			"Dostojevského rad",
			"Dvořákovo nábrežie",
			"Fajnorovo nábrežie",
			"Františkánske námestie",
			"Fraňa Kráľa",
			"Godrova",
			"Gondova",
			"Gorkého",
			"Gorkého, Bratislava",
			"Gunduličova",
			"Heydukova",
			"Hlavné námestie",
			"Hlboká cesta",
			"Hodžovo námestie",
			"Hurbanovo námestie",
			"Hviezdoslavovo námestie",
			"Imricha Karvaša",
			"Jesenského",
			"Jozefská",
			"Kapitulská",
			"Kapucínska",
			"Klariská",
			"Klobučnícka",
			"Konventná",
			"Kostolná",
			"Laurinská",
			"Lazaretská",
			"Lehockého",
			"Lermontovova",
			"Michalská",
			"Mikulášska",
			"Mišíkova",
			"Mýtna",
			"Na vŕšku",
			"Novosvetská",
			"Námestie 1. mája",
			"Námestie Alexandra Dubčeka",
			"Námestie SNP",
			"Námestie slobody",
			"Námestie Ľudovíta Štúra",
			"Obchodná",
			"Palisády",
			"Panenská",
			"Panská",
			"Podjavorinskej",
			"Povraznícka",
			"Pražská",
			"Prepoštská",
			"Primaciálne námestie",
			"Radlinského",
			"Radničná",
			"Riečna",
			"Rudnayovo námestie",
			"Rybné námestie",
			"Sedlárska",
			"Sienkiewiczova",
			"Staromestská",
			"Suché mýto",
			"Svoradova",
			"Tobrucká",
			"Tolstého",
			"Uršulínska",
			"Vajanského nábrežie",
			"Vazovova",
			"Ventúrska",
			"Vysoká",
			"Zochova",
			"Záhrebská",
			"Zámocká",
			"Zámočnícka",
			"Šafárikovo námestie",
			"Šancová",
			"Škarniclova",
			"Špitálska",
			"Štefanovičova",
			"Štefánikova",
			"Štetinova",
			"Štúrova",
			"Župné námestie",	
	};

	private LocationHelper mLocationHelper;
	
	 public void onCreate(Bundle savedInstance) {
 		super.onCreate(savedInstance);
 		
 		setContentView(R.layout.location_new);
 		
 		AutoCompleteTextView name = (AutoCompleteTextView) findViewById(R.id.name_field);
 		ArrayAdapter<String> adapter = new ArrayAdapter<String>(LocationNew.this, R.layout.auto_complete_item, R.id.text1, streets);
 		name.setAdapter(adapter);
 		
 		name.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					
					SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
					String preferenceValue = preferences.getString("city", null);
					if (preferenceValue != null)
						new MakeRequestTaskAdress().execute(String.valueOf(v.getText()) + ", " + preferenceValue);
					else
						new MakeRequestTaskAdress().execute(String.valueOf(v.getText()));	
		        }
				return false;
			}
		});
 		
 		
      }
	 
	 public void updateLocation(){
		 
		 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		 String preferenceValue = preferences.getString("yourPreferenceKey", null);
		 
		 if (preferenceValue != null)
			 return;
		 
		 
	 }
	 
	@Override
	protected void onDestroy() {
		super.onDestroy();		
	}
	 	 
	private static GeocodeResponse makeRequest(Context cnt, URL url) {	
		Reader reader;
		HttpClient httpclient = new DefaultHttpClient();
				
		try {
			HttpUriRequest request = new HttpGet(url.toURI());
			
			HttpResponse response = httpclient.execute(request);
			
			reader = new InputStreamReader(response.getEntity().getContent());
			Gson gson = new Gson();        

	        GeocodeResponse result = gson.fromJson(reader, GeocodeResponse.class);    
	        reader.close();
	        return result;
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static GeocodeResponse getResponseByAddress(Context cnt, String adress) {
		URL url;
		try {
			url = new URL("http://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(adress) + "&sensor=false");
			return makeRequest(cnt, url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static GeocodeResponse getResponseByLocation(Context cnt, String lat, String lng){
		URL url;
		try {
			url = new URL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + URLEncoder.encode(lat) + "," + URLEncoder.encode(lng) + "&sensor=false");
			return makeRequest(cnt, url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private class MakeRequestTaskAdress extends AsyncTask<String, Void, GeocodeResponse> {
		
		 protected void onPreExecute() {
			 
		 }
		
	     protected GeocodeResponse doInBackground(String... adress) {
	         return LocationNew.getResponseByAddress(getApplicationContext() ,adress[0]);
	     }

	     protected void onPostExecute(GeocodeResponse result) {
	    	 Log.d("task", "remove footer");
	    	 if (result != null && result.results.size() > 0){
	    		 ((TextView) findViewById(R.id.text1)).setText(result.results.get(0).formatted_address);
	    		 ((TextView) findViewById(R.id.text2)).setText(result.results.get(0).getAdressComponentType(GeocodeResponseResultColumns.ADMINISTRATIVE_AREA_LEVEL_1));
	    		 ((TextView) findViewById(R.id.text3)).setText(result.results.get(0).geometry.location.lat + ", " + result.results.get(0).geometry.location.lng);
	    		 
	    		 List<String> locations = new ArrayList<String>();
	    		 for(GeocodeResponseResult item : result.results){
	    			 locations.add(item.formatted_address);
	    		 }
	    		 
	    		 ArrayAdapter<String> adapter = new ArrayAdapter<String>(LocationNew.this, R.layout.auto_complete_item, R.id.text1, locations.toArray(new String[]{}));
	    		 ((AutoCompleteTextView) findViewById(R.id.name_field)).setAdapter(adapter);
	    		 ((AutoCompleteTextView) findViewById(R.id.name_field)).showDropDown();
	    	 }

	     }
	}
	
	private class MakeRequestTaskLocation extends AsyncTask<String, Void, GeocodeResponse> {
		
		 protected void onPreExecute() {
			 
		 }
		
	     protected GeocodeResponse doInBackground(String... location) {
	         return LocationNew.getResponseByLocation(getApplicationContext() ,location[0], location[1]);
	     }

	     protected void onPostExecute(GeocodeResponse result) {
	    	 Log.d("task", "remove footer");
	    	 if (result != null && result.results.size() > 0){
				GeocodeResponseResult locality = result.getLocality();
				if (locality == null)
					return;
	    		 	    		 
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString("city", locality.getAdressComponentType(GeocodeResponseResultColumns.LOCALITY));
				editor.commit();
				
				Toast.makeText(getBaseContext(), "Locality set to: " + locality.getAdressComponentType(GeocodeResponseResultColumns.LOCALITY), Toast.LENGTH_SHORT).show();
	    	 }

	     }
	 }
}
